#!/bin/bash
# 生产环境备份监控脚本
# 1. 备份源   2. 完整性  3. 告警  4. 日志轮滚

set -euo pipefail

BACKUP_DIR="/backup"               # 本地备份目录
REMOTE_DIR="s3://prod-backup"      # 远程备份桶
DB_NAME="prod"                     # 数据库名
DB_USER="backup"
DB_PASS="backup123"
MAIL_TO="ops@company.com"
THRESHOLD_DAYS=7                   # 备份保留天数

LOG_DIR="/var/log/backup"
LOG_FILE="${LOG_DIR}/backup-$(date +%F).log"
mkdir -p "$LOG_DIR"

log() {
    echo "$(date '+%F %T') $*" | tee -a "$LOG_FILE" | logger -t backup-monitor
}

# ---------- 1. 备份 ----------
do_backup() {
    log "开始备份..."
    # 文件备份
    tar -czf "$BACKUP_DIR/files-$(date +%Y%m%d_%H%M%S).tar.gz" /etc /var/www
    # 数据库备份
    mysqldump -u"$DB_USER" -p"$DB_PASS" "$DB_NAME" | gzip > "$BACKUP_DIR/db-$(date +%Y%m%d_%H%M%S).sql.gz"
}

# ---------- 2. 完整性校验 ----------
verify_backup() {
    local latest=$(ls -t "$BACKUP_DIR"/*.tar.gz | head -1)
    local sha256_latest=$(sha256sum "$latest" | awk '{print $1}')
    local sha256_remote=$(aws s3 cp "$REMOTE_DIR/$(basename "$latest")" - 2>/dev/null | sha256sum | awk '{print $1}' || echo "NONE")

    if [[ "$sha256_latest" != "$sha256_remote" ]]; then
        log "ERROR: 备份校验失败 $(basename "$latest")"
        return 1
    fi
    log "INFO: 备份校验通过 $(basename "$latest")"
}

# ---------- 3. 清理旧数据 ----------
cleanup() {
    find "$BACKUP_DIR" -type f -mtime +"$THRESHOLD_DAYS" -delete
    aws s3 rm "$REMOTE_DIR" --recursive --exclude "*" --include "*" --older-than "$THRESHOLD_DAYS"
    log "INFO: 清理 $THRESHOLD_DAYS 天前备份完成"
}

# ---------- 4. 邮件告警 ----------
send_alert() {
    local msg="$1"
    echo "$msg" | mail -s "Backup Monitor Alert $(hostname)" "$MAIL_TO"
    log "ALERT: 邮件已发送 $msg"
}

# ---------- 5. 主流程 ----------
main() {
    do_backup
    if verify_backup; then
        aws s3 sync "$BACKUP_DIR/" "$REMOTE_DIR/" --delete
        cleanup
        log "INFO: 备份监控完成"
    else
        send_alert "备份校验失败，请立即处理！"
        exit 1
    fi
}

main